import storage from "./storage.js";
import utils from "./utils.js";

const initList = async () => {
  const type = (await storage.get('special-type')) || 'black';
  const list = (await storage.get('special-list')) || {
    black: [],
    white: [],
  }
  list.white = list.white.map(item => item.trim()).filter(item => !!item);
  list.black = list.black.map(item => item.trim()).filter(item => !!item);
  return {type, list}
}
export default {
  enable() {
    return new Promise(async resolve => {
      const {type, list} = await initList();
      const {host, hostname, port, protocol} = new URL(await storage.getApiUrl())
      let proxyConfig = type === 'white' ? {
        mode: 'pac_script',
        pacScript: {
          data: `
            let proxy = '${host}'
            const type = '${type}';
            const list = ${JSON.stringify(list)}[type];
            function FindProxyForURL(url, host){
              for (var i = list.length - 1; i >= 0; i--) {
                if (shExpMatch(host, list[i])) {
                  return ('PROXY ' + proxy);
                }
              }
            }
          `
        }
      } : {
        mode: 'fixed_servers',
        rules: {
          singleProxy: {
            scheme: protocol.replace(/:/g, ''),
            host: hostname,
            port: +port
          },
          bypassList: ["<-loopback>", ...list.black]
        }
      };
      chrome.proxy.settings.set({value: proxyConfig, scope: 'regular'}, function () {
        resolve();
      });
    });
  },
  disable() {
    return new Promise(resolve => {
      chrome.proxy.settings.set({value: {mode: 'system'}, scope: 'regular'}, function () {
        resolve();
      })
    });
  },
  get() {
    return new Promise(resolve => {
      chrome.proxy.settings.get({incognito: false}, async config => {
        let hasEnableWhistleProxy = ['fixed_servers', 'pac_script'].includes(config.value.mode);
        hasEnableWhistleProxy ? utils.setTitle(`${chrome.i18n.getMessage('enableTipBackground')}${await storage.getApiUrl()}`) : utils.setTitle(chrome.i18n.getMessage('disableTipBackground'));
        chrome.action.setIcon({
          path: hasEnableWhistleProxy ? 'icon.png' : 'icon_disabled.png'
        });
        resolve(hasEnableWhistleProxy);
      });
    });
  },
  initList
}

